package com.basin.micro.uplaod.task;

import cn.hutool.extra.spring.SpringUtil;
import com.basin.common.core.async.standard.AbstractBaseTask;
import com.basin.common.core.exception.BasinException;
import com.basin.common.oss.component.BasinUploadManager;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
public class UploadTask extends AbstractBaseTask<String> {
    private String fileName;
    private MultipartFile multipartFile;
    private BasinUploadManager basinUploadManager;

    public UploadTask(MultipartFile multipartFile) {
        this.multipartFile = multipartFile;
        this.open();
    }

    @Override
    public void open() {
        this.basinUploadManager = SpringUtil.getBean(BasinUploadManager.class);
        if (this.basinUploadManager == null) {
            throw new BasinException("获取上传管理器实例为空");
        }
    }

    @Override
    public String execute() throws Exception {
        if (this.multipartFile == null) {
            throw new BasinException("上传文件为空");
        }
        String fileName = System.currentTimeMillis() + "_" + this.multipartFile.getOriginalFilename();
        return this.basinUploadManager.upload(fileName, this.multipartFile.getBytes());
    }

    @Override
    public void callback() {
        this.multipartFile = null; // 任务执行完成后释放 MultipartFile 资源
    }

    public String getFileName() {
        return this.fileName;
    }
}
